package com.yuexun.dhdoctor.module.departmentDocumentNew.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.yuexun.dhdoctor.R;
import com.yuexun.dhdoctor.base.BaseEntity;
import com.yuexun.dhdoctor.baselistener.OnItemPartClickListener;
import com.yuexun.dhdoctor.baselistener.OnItemPartClickListener02;
import com.yuexun.dhdoctor.config.AppConfig;
import com.yuexun.dhdoctor.module.departmentDocumentNew.Act_Document_Share_My_MemberList;
import com.yuexun.dhdoctor.module.departmentDocumentNew.adapter.DocMyShareAdapter;
import com.yuexun.dhdoctor.module.departmentDocumentNew.bean.DocDepartBean;
import com.yuexun.dhdoctor.module.departmentDocumentNew.bean.ShareDocBean;
import com.yuexun.dhdoctor.module.departmentDocumentNew.model.impl.ShareDocModel;
import com.yuexun.dhdoctor.module.departmentDocumentNew.model.impl.UserDepartDocTreeModel;
import com.yuexun.dhdoctor.module.departmentDocumentNew.presenter.impl.CancelShareDocPresenter;
import com.yuexun.dhdoctor.module.departmentDocumentNew.presenter.impl.ShareDocPresenter;
import com.yuexun.dhdoctor.module.departmentDocumentNew.presenter.impl.UserDepartDocTreePresenter;
import com.yuexun.dhdoctor.module.departmentDocumentNew.view.ICancelShareDocView;
import com.yuexun.dhdoctor.module.departmentDocumentNew.view.IShareDocView;
import com.yuexun.dhdoctor.module.departmentDocumentNew.view.IUserDepartDocTreeView;
import com.yuexun.dhdoctor.util.ListChangeUtil;
import com.yuexun.dhdoctor.widget.EmptyLayout;
import com.yuexun.dhdoctor.widget.LoadingDialog;
import com.yuexun.dhdoctor.widget.PullToRefresh.FooterLoadingLayout;
import com.yuexun.dhdoctor.widget.PullToRefresh.PullToRefreshBase;
import com.yuexun.dhdoctor.widget.PullToRefresh.PullToRefreshList;


import org.kymjs.kjframe.ui.KJFragment;
import org.kymjs.kjframe.ui.ViewInject;
import org.kymjs.kjframe.utils.PreferenceHelper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Administrator on 2018/11/28 0028.
 */

public class Frag_Doc_My_Share_New extends KJFragment implements IShareDocView, ICancelShareDocView
    ,IUserDepartDocTreeView {

    @Bind(R.id.et_doc_my)
    EditText etSearch;

    @Bind(R.id.empty_layout)
    EmptyLayout emptyLayout;
    @Bind(R.id.lv_doc_my)
    PullToRefreshList mPullRefreshListView;
    @Bind(R.id.rl_doc_my_share)
    RelativeLayout rlShare;
    @Bind(R.id.cb_doc_my_all)
    CheckBox cbAll;
    @Bind(R.id.tv_edit)
    TextView tvEdit;

    //当前页
    private int nowpage = 1;
    private int pagesize = 999;
    //当前科室
    private DocDepartBean nowDepart;

    private ShareDocPresenter shareDocPresenter;
    private DocMyShareAdapter adapterDoc;
    private List<ShareDocBean> docDatas = new ArrayList<>();

    private CancelShareDocPresenter cancelSharePredenter;

    private LoadingDialog loadingDialog;

    private UserDepartDocTreePresenter docDepartPresenter;

    @Override
    protected View inflaterView(LayoutInflater inflater, ViewGroup container, Bundle bundle) {
        View view = inflater.inflate(R.layout.frag_doc_my_share_new, null);
        ButterKnife.bind(this, view);
        initView();
        return view;
    }

    private void initView() {
        loadingDialog = new LoadingDialog(getActivity());
        shareDocPresenter = new ShareDocPresenter(this, new ShareDocModel());
        cancelSharePredenter = new CancelShareDocPresenter(this, new ShareDocModel());
        docDepartPresenter = new UserDepartDocTreePresenter(this, new UserDepartDocTreeModel());
//        nowDepart = ((Act_Document_New) getActivity()).myDepartItem;

        emptyLayout.setErrorType(EmptyLayout.NETWORK_LOADING);
//        ApiGetDocDatas("");

        etSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView arg0, int arg1, KeyEvent arg2) {
                if (arg1 == EditorInfo.IME_ACTION_SEARCH) {
                    nowpage = 1;
                    emptyLayout.setErrorType(EmptyLayout.NETWORK_LOADING);
                    ApiGetDocDatas(etSearch.getText().toString().trim());
                }
                return false;
            }
        });

        initListView();
        cbAll.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                setAllSelect(isChecked);
            }
        });
    }

    //初始化列表
    private void initListView() {
        mPullRefreshListView.setPullRefreshEnabled(false);
        mPullRefreshListView.setPullLoadEnabled(false);//设置上拉加载功能
        ((FooterLoadingLayout) mPullRefreshListView.getFooterLoadingLayout()).setNoMoreDataText("已经是最新状态");
        ListView mList = mPullRefreshListView.getRefreshView();
        mList.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
        adapterDoc = new DocMyShareAdapter(mList, docDatas, R.layout.item_doc_my_share);
        mList.setAdapter(adapterDoc);
        adapterDoc.SetOnItemPartClickListener(new OnItemPartClickListener02() {
            @Override
            public void OnClick(int position) {
                Bundle bundle = new Bundle();
                bundle.putSerializable("docinfo", docDatas.get(position));
                Intent intent = new Intent(getActivity(), Act_Document_Share_My_MemberList.class);
                intent.putExtras(bundle);
                startActivityForResult(intent, 1);
            }
        });

        mPullRefreshListView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                nowpage = nowpage + 1;
                ApiGetDocDatas("");
            }
        });
        ApiGetFile();
    }

    private void ApiGetFile(){
        Map<String, String> params = new HashMap<>();
        params.put("sessionUuid", PreferenceHelper.readString(getActivity(), AppConfig.USER_INFO, AppConfig.SESSION_ID));
        docDepartPresenter.getDepartTree(params);
    }

    //设置文档列表请求
    private void ApiGetDocDatas(String key) {
        emptyLayout.setErrorType(EmptyLayout.NETWORK_LOADING);
        Map<String, String> params = new HashMap<>();
        params.put("sessionUuid", PreferenceHelper.readString(getActivity(), AppConfig.USER_INFO, AppConfig.SESSION_ID));
        params.put("departDocId", nowDepart.getDepartDocId());
        params.put("docType", nowDepart.getDocType() + "");
        params.put("pageIndex", nowpage + "");
        params.put("pageSize", pagesize + "");
        params.put("inquireKey", key);
        shareDocPresenter.getShareDocDatas(params);
    }

    @Override
    public void showShareDocDatas(BaseEntity<ShareDocBean> getShareDocDatas) {
        if (mPullRefreshListView.isPullRefreshEnabled()) {
            mPullRefreshListView.onPullDownRefreshComplete();
        }


        if ("200".equals(getShareDocDatas.getStatus())) {
            if (getShareDocDatas.getDatas().size() == 0) {
                mPullRefreshListView.setHasMoreData(false);
            } else {
                if (mPullRefreshListView.isPullLoadEnabled()) {
                    mPullRefreshListView.onPullUpRefreshComplete();
                }
            }

            if (nowpage == 1) {
                docDatas.clear();
                docDatas = getShareDocDatas.getDatas();
            } else {
                docDatas.addAll(getShareDocDatas.getDatas());
            }
            adapterDoc.refresh(docDatas);
        } else {
            ViewInject.toast(getShareDocDatas.getMessage());
        }

        if (docDatas.size() > 0) {
            emptyLayout.dismiss();
        } else {
            emptyLayout.setErrorType(EmptyLayout.NODATA);
        }
    }


    @Override
    @OnClick({R.id.btn_doc_my_share, R.id.tv_doc_my_search,R.id.tv_edit,R.id.btn_doc_my_edit})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_doc_my_share:
                setShare();
                break;
            case R.id.tv_doc_my_search:
                nowpage = 1;
                emptyLayout.setErrorType(EmptyLayout.NETWORK_LOADING);
                ApiGetDocDatas(etSearch.getText().toString().trim());
                break;
            case R.id.tv_edit:
                tvEdit.setVisibility(View.GONE);
                rlShare.setVisibility(View.VISIBLE);
                showDown(true);
                break;
            case R.id.btn_doc_my_edit:
                tvEdit.setVisibility(View.VISIBLE);
                rlShare.setVisibility(View.GONE);
                showDown(false);
                break;
        }
    }

    //设置显示下载
    public void showDown(boolean is) {
        if (is) {
            adapterDoc.setDo(true);
        } else {
            adapterDoc.setDo(false);
        }
    }

    //设置全选
    public void setAllSelect(boolean isChecked) {
        if (isChecked) {
            for (ShareDocBean beanDate : docDatas) {
                beanDate.setSelect(true);
            }
        } else {
            for (ShareDocBean beanDate : docDatas) {
                beanDate.setSelect(false);
            }
        }
        adapterDoc.notifyDataSetChanged();
    }

    //设置共享
    public void setShare() {
        List<String> docIds = new ArrayList<>();
        List<String> docFileTypes = new ArrayList<>();
        for (ShareDocBean beanDate : docDatas) {
            if (beanDate.isSelect()) {
                docIds.add("b_" + beanDate.getDocId());
                docFileTypes.add(beanDate.getFileType() + "");
            }
        }
        if (docIds.size() > 0) {
            String strIds = ListChangeUtil.listToString(docIds, ";");
            String strFileType = ListChangeUtil.listToString(docFileTypes, ";");

            loadingDialog.show();
            Map<String, String> params = new HashMap<>();
            params.put("sessionUuid", PreferenceHelper.readString(getActivity(), AppConfig.USER_INFO, AppConfig.SESSION_ID));
            params.put("departDocId", strIds);
            params.put("fileType", strFileType);
            cancelSharePredenter.calcelShareDoc(params);
        } else {
            ViewInject.toast("请选择文件");
        }
    }

    @Override
    public void calcelShareDoc(BaseEntity<String> bean) {
        if ("200".equals(bean.getStatus())) {
            loadingDialog.dismiss();
            nowpage = 1;
            ApiGetDocDatas("");
        } else {
            ViewInject.toast("取消文档共享失败");
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            nowpage = 1;
            ApiGetDocDatas(etSearch.getText().toString().trim());
        }
    }

    @Override
    public void showDepartTree(BaseEntity<DocDepartBean> getDepartTree) {
        if ("200".equals(getDepartTree.getStatus())) {
            ArrayList<DocDepartBean> departDatas;
            departDatas = getDepartTree.getDatas();
            for (DocDepartBean item : departDatas) {
                if (item.getDepartDocId().equals("s_0")) {
                    nowDepart = item;
                    ApiGetDocDatas("");
                }
            }
        }
    }
}
